//
//  WPCHomepageViewController.m
//  Wallpaper.co
//
//  Created by zhou_yuepeng on 2017/8/31.
//  Copyright © 2017年 www.dahuatech.com. All rights reserved.
//

#import "WPCHomepageViewController.h"
#import "WPCHomepageView.h"
#import "WPCHomepageViewCell.h"
#import "WPCHomepagePresenter.h"
#import "MJRefresh.h"
#import "WPCPreviewView.h"
#import "WPCLayout.h"
#import "WPCOrderView.h"

@interface WPCHomepageViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>
@property(nonatomic, strong) UICollectionViewFlowLayout *layout;
@property(nonatomic, strong) WPCHomepageView            *collectionView;
@property(nonatomic, strong) WPCHomepagePresenter       *presenter;

@property(nonatomic, copy) NSString                     *mTag;
@property(nonatomic, copy) NSString                     *mTitle;
@property(nonatomic, assign) NSInteger                   mPage;

@property(nonatomic, strong) UIButton                   *logoBtn;
@property(nonatomic, strong) WPCOrderView               *orderView;

@property(nonatomic, strong) UIActivityIndicatorView    *loadingView;
@end

@implementation WPCHomepageViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        _presenter = [[WPCHomepagePresenter alloc] init];
        [_presenter attachController:self];
        
        _layout = [[UICollectionViewFlowLayout alloc] init];
        _layout.minimumInteritemSpacing = 1;
        _layout.minimumLineSpacing = 1;
        
        self.collectionView = [[WPCHomepageView alloc] initWithFrame:[[UIScreen mainScreen] bounds] collectionViewLayout:_layout cellIdentifier:[WPCHomepageViewCell cellIdentifier]];
        self.collectionView.delegate = self;
        self.collectionView.dataSource = self;
        [self.view addSubview:self.collectionView];
        
        /* 上拉加载 */
        self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            if (_mPage == _presenter.totalPage) {
                [self.collectionView.mj_footer endRefreshing];
                return;
            }
            
            _mPage ++;            
            [_presenter refreshHomepageWithTag:_mTag page:_mPage reload:NO callback:^(BOOL result) {
                [self.collectionView.mj_footer endRefreshing];
                
                if (result) {
                    [self updateData];
                } else {
                    NSLog(@"refreshHomepageWithTag failed!!!\r\n");
                }
            }];
        }];
        
        _logoBtn = [[UIButton alloc] init];
        _logoBtn.tag = BTN_LOGO;
        [_logoBtn setImage:[UIImage imageNamed:@"logo"] forState:UIControlStateNormal];
        [self.view addSubview:_logoBtn];
        [_logoBtn addTarget:self action:@selector(onTouchUp:) forControlEvents:UIControlEventTouchUpInside];
        
        _orderView = [[WPCOrderView alloc] init];
        [self.view addSubview:_orderView];
        
        _loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        _loadingView.hidden = YES;
        [self.view addSubview:_loadingView];
        
        [self layoutWithMasonry];
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.transitioningDelegate = self;
    [self addScreenEdgePanGestureRecognizer:self.view edges:UIRectEdgeLeft];
}

- (void)updateData
{
    dispatch_async(dispatch_get_main_queue(), ^{
        _orderView.orderModel.tagName = _mTitle;
        _orderView.orderModel.currentPage = 1;
        _orderView.orderModel.totalPage = _presenter.totalPage;
        
        [self.collectionView reloadData];
    });
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSInteger number = _presenter.themesCount;
    if (0 == number) {
        number = 12;
    }
    return number;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    WPCHomepageViewCell *cell = (WPCHomepageViewCell*)[self.collectionView cellForItemWithIndexPath:indexPath];
    NSInteger pageOut = 0;
    [cell loadImageWithURL:[_presenter themesItemAtIndex:indexPath.row pageOut:&pageOut].thumbnailURL];
    _orderView.orderModel.currentPage = pageOut;
    return cell;
}

#pragma mark <UICollectionViewDelegate>
//定义每一个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(124, 222);
}


- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
     /* 显示预览界面 */
    [_presenter previewWallpaper:indexPath.row];
     
    return YES;
}

#pragma Mark - UIViewControllerTransitioningDelegate
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    return [[WPCPresentTransitionAnimated alloc] initWithDuration:0.1 type:_animatedType];
}

// 百分比present
- (id<UIViewControllerInteractiveTransitioning>)interactionControllerForPresentation:(id<UIViewControllerAnimatedTransitioning>)animator{
    return _percentDrivenTransition;
}

// 百分比dismiss
- (id<UIViewControllerInteractiveTransitioning>)interactionControllerForDismissal:(id<UIViewControllerAnimatedTransitioning>)animator{
    return _percentDrivenTransition;
}

#pragma mark <private method>
- (void)layoutWithMasonry
{
    [_logoBtn makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.collectionView).offset(5);
        make.top.equalTo(self.collectionView).offset(5);
        make.size.equalTo(CGSizeMake(30, 30));
    }];
    
    [_orderView makeConstraints:^(MASConstraintMaker *make) {
        CGFloat percentWidth = 0.6;
        make.left.equalTo(self.collectionView).offset(self.view.bounds.size.width * (1.0 - percentWidth));
        make.top.equalTo(self.view.bottom).offset(-30);
        make.size.equalTo(CGSizeMake(self.view.bounds.size.width * percentWidth, 30));
    }];
    
    [_loadingView makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
    }];
}

- (void)onTouchUp:(id)sender
{
    UIView *tmp = (UIView*)sender;
    if (BTN_LOGO == tmp.tag) {
        NSLog(@"logo按钮被点击\n");
        [_presenter showLeftSidebar];
    }
}

// 添加手势的方法
- (void)addScreenEdgePanGestureRecognizer:(UIView *)view edges:(UIRectEdge)edges
{
    // viewController和SecondViewController的手势都由self管理
    UIScreenEdgePanGestureRecognizer * edgePan = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(edgePanGesture:)];
    edgePan.edges = edges;
    [view addGestureRecognizer:edgePan];
}

// 手势的监听方法
- (void)edgePanGesture:(UIScreenEdgePanGestureRecognizer *)edgePan{
    // 有两个手势，所以这里计算百分比使用的是 KeyWindow
    CGFloat progress = fabs([edgePan translationInView:[UIApplication sharedApplication].keyWindow].x / [UIApplication sharedApplication].keyWindow.bounds.size.width);
    
    if(edgePan.state == UIGestureRecognizerStateBegan)
    {
        self.percentDrivenTransition = [[UIPercentDrivenInteractiveTransition alloc] init];
        if(edgePan.edges == UIRectEdgeLeft)
        {
            [_presenter showLeftSidebar];
        }
        else if(edgePan.edges == UIRectEdgeRight)
        {
            [self dismissViewControllerAnimated:NO completion:nil];
        }
    }
    else if(edgePan.state == UIGestureRecognizerStateChanged)
    {
        [self.percentDrivenTransition updateInteractiveTransition:progress];
    }
    else if(edgePan.state == UIGestureRecognizerStateCancelled || edgePan.state == UIGestureRecognizerStateEnded)
    {
        if(progress > 0.5)
        {
            [self.percentDrivenTransition finishInteractiveTransition];
        }else
        {
            [self.percentDrivenTransition cancelInteractiveTransition];
        }
        self.percentDrivenTransition = nil;
    }
}

#pragma mark <public method>
- (void)configControllerWithTag:(NSString*)tag title:(NSString*)title
{
    self.mTag = tag;
    self.mTitle = title;
    self.mPage = 1;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.view.userInteractionEnabled = NO;
        _loadingView.hidden = NO;
        [_loadingView startAnimating];
    });
    
    [_presenter refreshHomepageWithTag:_mTag page:_mPage reload:YES callback:^(BOOL result) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.view.userInteractionEnabled = YES;
            
            _loadingView.hidden = YES;
            [_loadingView stopAnimating];
        });
        
        if (result) {
            [self updateData];
            self.collectionView.contentOffset = CGPointMake(0, 0);
        } else {
            NSLog(@"refreshHomepageWithTag failed!!!\r\n");
        }
    }];
}

@end
